/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aviso.util;

/**
 *
 * @author avgusti
 */
import javax.faces.FacesException;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
public class LifeCycleListener implements PhaseListener {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    // private static final Log LOG = LogFactory.getLog("wlmp.ui.util");

    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

    public void beforePhase(PhaseEvent event) {
        // if(LOG.isTraceEnabled())  LOG.debug("START PHASE " + event.getPhaseId());
        FacesContext facesCtx = event.getFacesContext();
        ExternalContext extCtx = facesCtx.getExternalContext();
        Application app = facesCtx.getApplication();
        ViewHandler viewHandler = app.getViewHandler();

        HttpSession session = (HttpSession) extCtx.getSession(false);
        boolean newSession = (session == null) || (session.isNew());
        boolean postback = !extCtx.getRequestParameterMap().isEmpty();
        boolean timedout = postback && newSession;

        String id = viewHandler.deriveViewId(facesCtx, null);
        //viewHandler.getActionURL(facesCtx, id);

        if (timedout) {
            //      if(LOG.isTraceEnabled())  LOG.debug(" Session Time out do redirect to /error.xhtml ");

            facesCtx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Session Time Out !", ""));
            UIViewRoot view = viewHandler.createView(facesCtx, "/error.xhtml");
            facesCtx.setViewRoot(view);
            facesCtx.renderResponse();
            try {
                viewHandler.renderView(facesCtx, view);
                facesCtx.responseComplete();
            } catch (Throwable t) {
                throw new FacesException("Session timed out", t);
            }

        }
    }

    public void afterPhase(PhaseEvent event) {
        FacesContext facesCtx = event.getFacesContext();
        ExternalContext extCtx = facesCtx.getExternalContext();
        Application app = facesCtx.getApplication();
        ViewHandler viewHandler = app.getViewHandler();
        UIViewRoot root= facesCtx.getViewRoot();
        String id= (root!=null) ? root.getViewId():null;

    }
}